package asynchronous;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class AQSTest {
    public ReentrantLock lock = new ReentrantLock();
    Condition notEmpty = lock.newCondition();
    Condition notFull = lock.newCondition();
    int cap = 10;
    int size = 0;
    int[] queue = new int[cap];
    int putIndex = 0;
    int takeIndex = 0;
    public void put(int val) {
        lock.lock();
        try{
            queue[putIndex] = val;
            putIndex = ++putIndex == cap ? 0 : ++putIndex;
            size++;
            while (size == cap){
                notFull.await();
            }
            notEmpty.notifyAll();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public int get() {
        lock.lock();
        int val = 0;
        try {
            while (size == 0) {
                notEmpty.await();
            }
            val = queue[takeIndex];
            takeIndex = ++takeIndex == cap ? 0 : ++takeIndex;
            size--;
            notFull.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return val;
    }

}
